#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "../include/meta.h"
#include "../include/vfs_errorcodes.h"

char* cpy_file (char source_file_path[100],char dest_file_path[100])
{	

	//displayBstTree(bstroot);
	char result[100];
	if((strcmp(source_file_path,"")==0)||(strcmp(dest_file_path,"")==0))
		{
		strcpy(result,"copyfile_FAILURE ");
		strcat(result,ERR_VFS_COPYFILE_00);
		sprintf(str, "%s",result);
		return str;
		}

	if(root==NULL)
		{
		strcpy(result,"copyfile_FAILURE ");
		strcat(result,ERR_VFS_COPYFILE_05);
		sprintf(str, "%s",result);
		return str;
		}
//printf("@%s@  ",source_file_path);

	if(source_file_path[strlen(source_file_path)-4]!='.')
	{	if(source_file_path[strlen(source_file_path)-1]!='/')
		{ strcat(source_file_path,"/");
	   	 } 	
	}

//printf("@%s@\n",source_file_path);
	//char str[20],str1[20];
	//printf("I am inside copyfile\n");
	//printf("%s\n",source_file_path);
	//printf("%s\n",dest_file_path);
	
	int index2=bst_search(bstroot,dest_file_path);	
	//printf("Index2:%d",index2);
	int index=bst_search(bstroot,source_file_path);
	//printf("Index: %d \n",index);
	
	if(index==-1)
		{
		strcpy(result,"copyfile_FAILURE ");
		strcat(result,ERR_VFS_COPYFILE_01);
		sprintf(str, "%s",result);
		return str;
		}
	
	//printf("source_file_path type:%s\n",fd[index].file_type);
	if(strcmp(fd[index].file_type,"folder")==0)
		{
		strcpy(result,"copyfile_FAILURE ");
		strcat(result,ERR_VFS_COPYFILE_03);
		sprintf(str, "%s",result);
		return str;
		}

	if(index2==-1)
		{
		strcpy(result,"copyfile_FAILURE ");
		strcat(result,ERR_VFS_COPYFILE_02);
		sprintf(str, "%s",result);
		return str;
		}
			
	//printf("dest_file_path type:%s\n",fd[index2].file_type);
			
								
	FILE *fo, *fp; 
	fo=fopen(mounted_vfs,"rb+");
	fp=fopen(mounted_vfs,"rb+");
	
	//printf("Calculating offset");
	int offset = main_header_var->headersize + 1024*(fd[index].block_number);
	//printf("block:%d offset:%d",fd[index].block_number,offset);
					
	int offset1= main_header_var->headersize + 1024*(fd[index2].block_number);
	//printf("block:%d offset1:%d",fd[index2].block_number,offset1);
					
			
	fseek(fp,offset,SEEK_SET); 
	fseek(fo,offset1,SEEK_SET); //printf("fotell: %d ",ftell(fo));
	//char buffer[1024];
										
	int size= fd[index].file_size; //printf("list: %d, %d\n",index,size);
	char ch; int count=0;
									
	while(count<size)
		{	count++;
			ch= fgetc(fp); //printf(" %c",ch);
			fputc(ch,fo); 
		}
					
	fd[index2].file_size=size;

//	int seek=ftell(fo); 
//	fseek(fo,(seek-1),SEEK_SET);
//	ch= fgetc(fo); //printf("%d:%c",seek,ch);
	fputc(EOF,fo);
					
					
	fclose(fo);
	fclose(fp);
	
	
	strcpy(result,"copyfile_SUCCESS");
	char *ret=malloc(strlen(result));
	sprintf(ret, "%s",result);
	return ret;

}
